package com.ruoyi.common.utils;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author chenran
 * @description http 工具类
 * @date 2024/8/9 17:11
 */
@Slf4j
public class HttpClientUtil {

    static final int TIMEOUT_MSEC = 5 * 1000;
    private static final Gson GSON = new Gson();

    /**
     * 发送GET方式请求
     *
     * @param url
     * @param paramMap
     * @return
     */
    public static String doGet(String url, Map<String, String> paramMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String result = "";
        CloseableHttpResponse response = null;
        try {
            URIBuilder builder = new URIBuilder(url);
            if (paramMap != null) {
                for (String key : paramMap.keySet()) {
                    builder.addParameter(key, paramMap.get(key));
                }
            }
            URI uri = builder.build();
            //创建GET请求
            HttpGet httpGet = new HttpGet(uri);
            //发送请求
            response = httpClient.execute(httpGet);
            //判断响应状态
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 发送POST请求（同时支持URL参数和JSON body）
     *
     * @param url       请求URL
     * @param urlParams URL参数（查询字符串）
     * @param jsonBody  JSON请求体
     * @return 响应结果
     * @throws IOException
     */
    public static String doPost(String url, Map<String, String> urlParams, String jsonBody) throws IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 构建带URL参数的完整URL
            String finalUrl = buildUrlWithParams(url, urlParams);

            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(finalUrl);

            // 设置JSON body
            if (jsonBody != null && !jsonBody.trim().isEmpty()) {
                StringEntity entity = new StringEntity(jsonBody, "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            // 如果没有JSON body，检查是否有表单参数（向后兼容）
            else if (urlParams != null && !urlParams.isEmpty()) {
                // 这里保持向后兼容，将urlParams作为表单参数处理
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> param : urlParams.entrySet()) {
                    paramList.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                httpPost.setEntity(entity);
            }
            // 如果既没有JSON body也没有参数，发送空请求
            else {
                log.info("发送空POST请求 - URL: {}", url);
            }
            httpPost.setConfig(builderRequestConfig());
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                log.error("关闭HTTP连接异常: {}", e.getMessage(), e);
            }
        }
        return resultString;
    }

    /**
     * 构建带参数的URL
     */
    private static String buildUrlWithParams(String url, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return url;
        }

        try {
            URIBuilder builder = new URIBuilder(url);
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.addParameter(entry.getKey(), entry.getValue());
            }
            return builder.build().toString();
        } catch (Exception e) {
            log.warn("构建URL参数失败，使用原始URL: {}", e.getMessage());
            return url;
        }
    }

    /**
     * 专门用于发送JSON请求的便捷方法（Map自动转JSON + URL参数）
     */
    public static String doPostJson(String url, Map<String, String> urlParams, Map<String, Object> jsonParamMap) throws IOException {
        String jsonBody = GSON.toJson(jsonParamMap);
        return doPost(url, urlParams, jsonBody);
    }

    private static RequestConfig builderRequestConfig() {
        return RequestConfig.custom()
            .setConnectTimeout(TIMEOUT_MSEC)
            .setConnectionRequestTimeout(TIMEOUT_MSEC)
            .setSocketTimeout(TIMEOUT_MSEC).build();
    }


    /**
     * 发送POST请求并返回字节数组（用于处理二进制响应如图片）
     *
     * @param url       请求URL
     * @param urlParams URL参数（查询字符串）
     * @param jsonBody  JSON请求体
     * @return 响应字节数组
     * @throws IOException
     */
    public static byte[] doPostAndGetBytes(String url, Map<String, String> urlParams, Object jsonBody) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 构建带URL参数的完整URL
            String finalUrl = buildUrlWithParams(url, urlParams);

            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(finalUrl);

            // 设置JSON body
            if (jsonBody != null) {
                String jsonString;
                if (jsonBody instanceof String) {
                    jsonString = (String) jsonBody;
                } else {
                    // 使用Gson或其他JSON库将对象转换为字符串
                    Gson gson = new Gson();
                    jsonString = gson.toJson(jsonBody);
                }

                StringEntity entity = new StringEntity(jsonString, "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }

            httpPost.setConfig(builderRequestConfig());

            // 执行http请求
            response = httpClient.execute(httpPost);

            // 直接读取字节数组，不进行字符编码转换
            return EntityUtils.toByteArray(response.getEntity());

        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                log.error("关闭HTTP连接异常: {}", e.getMessage(), e);
            }
        }
    }


}
